package com.muqi.app.qlearn.student;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.R.integer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMConversation.EMConversationType;
import com.easemob.chat.EMMessage;
import com.easemob.easeui.EaseConstant;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.loader.GlideImageLoader;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.menu.button.capricorn.ArcMenu;
import com.muqi.app.im.qmain.Constant;
import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.application.ActivitiesStack;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.CustomerUtil;
import com.muqi.app.project.utils.LogUtil;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.fragments.TabChat;
import com.muqi.app.qlearn.fragments.TabFileTree;
import com.muqi.app.qlearn.fragments.TabGrow;
import com.muqi.app.qlearn.fragments.TabGrowTree;
import com.muqi.app.qlearn.fragments.TabHome;
import com.muqi.app.qlearn.fragments.TabHomeNew;
import com.muqi.app.qlearn.fragments.TabMine;
import com.muqi.app.qlearn.login.LoginActivity;
import com.muqi.app.qlearn.modles.ChildInfo;
import com.muqi.app.qlearn.modles.TreeHomeBean;
import com.muqi.app.qlearn.modles.UClassInfo;
import com.muqi.app.qlearn.modles.UserInfo;
import com.muqi.app.qlearn.publish.WriteRecordActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.BodyActivity;
import com.muqi.app.qlearn.ui.MyHomeWkDetailsActivity;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.db.CupboardSQLiteOpenHelper;
import com.muqi.app.user.db.MyClassStudent;
import com.muqi.app.user.db.TreeLeaf;
import com.muqi.app.user.widget.MenuWindow;
import com.muqi.app.user.widget.MenuWindow.ClickMenuItemListener;
import com.zhy.m.permission.MPermissions;

public class MenuActivity extends BaseFragmentActivity implements
		RadioGroup.OnCheckedChangeListener, EMEventListener,
		ClickMenuItemListener {
	public static final int GET_IMAGE_VIA_CAMERA = 1002;
	private static final int[] ITEM_DRAWABLES = { R.drawable.icon_record,
			R.drawable.icon_camera, R.drawable.icon_album };

	private RadioGroup mBottomRdg;
	private RadioButton rb_center;
	private RelativeLayout main_root;
	private TabHomeNew home_pager;
	//private TabGrow live_pager;
	//private TabFileTree file_page;
	private TabChat chat_pager;
	private TabMine mine_pager;
	private TabGrowTree tabGrowTree;
	private FragmentManager manager;
	// 未读消息textview
	private TextView unreadLabel;
	// 作业陪伴textview
	private TextView unshowLabel;
	// 账号在别处登录
	public boolean isConflict = false;
	// 账号被移除
	private boolean isCurrentAccountRemoved = false;
	private BroadcastReceiver broadcastReceiver;
	private LocalBroadcastManager broadcastManager;
	private BroadcastReceiver childReceiver;
	public static MenuActivity instance;

	private ImageView mBottomBg;
	private boolean isFileTree = false;

	private CupboardSQLiteOpenHelper dbHelper;
	private SQLiteDatabase sqlDb;
	private ArcMenu arcMenu;
	private MenuWindow menuWindow;

	private ImagePicker imagePicker;
	private List<ImageItem> postImages = new ArrayList<ImageItem>();
	private UserInfo userinfo;

	private int oldTreeLeaf = -1;
	private int position;
	private boolean isMine;

	/**
	 * 检查当前用户是否被删除
	 */
	public boolean getCurrentAccountRemoved() {
		return isCurrentAccountRemoved;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
		if (savedInstanceState != null
				&& savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED,
						false)) {
			// 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
			// 5个fragment里加的判断同理
			EMHelper.getInstance().logout(true, null);
			finish();
			startActivity(LoginActivity.class);
			return;
		} else if (savedInstanceState != null
				&& savedInstanceState.getBoolean("isConflict", false)) {
			// 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
			// 5个fragment里加的判断同理
			finish();
			startActivity(LoginActivity.class);
			return;
		}
		setContentView(R.layout.aty_menu);
		showTabHome();
		if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)
				&& !isConflictDialogShow) {
			showConflictDialog();
		} else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false)
				&& !isAccountRemovedDialogShow) {
			showAccountRemovedDialog();
		}
	}

	@Override
	public void onEvent(EMNotifierEvent event) {
		EMMessage message = null;
		if (event.getData() instanceof EMMessage) {
			message = (EMMessage) event.getData();
		}
		switch (event.getEvent()) {
		case EventNewMessage: // 普通消息
			EMHelper.getInstance().getNotifier().onNewMsg(message);
			refreshUIWithMessage();
			break;
		case EventOfflineMessage:
			refreshUIWithMessage();
			break;
		case EventConversationListChanged:
			break;
		case EventNewCMDMessage:
			CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
			final String action = cmdMsgBody.action;// 获取自定义action
			setCmdMessage(action, message);
			break;
		default:
			break;
		}
	}

	private void refreshUIWithMessage() {
		runOnUiThread(new Runnable() {
			public void run() {
				// 刷新bottom bar消息未读数
				updateUnreadLabel();
			}
		});
	}

	public void updateTreeLabel() {

		TreeLeaf leaf = cupboard().withDatabase(sqlDb).query(TreeLeaf.class)
				.withSelection("child_id = ?", mSpUtil.getCurrentChildId())
				.get();
		if (leaf != null) {
			if (leaf.hasShow) {
				unshowLabel.setVisibility(View.INVISIBLE);
			} else {
				unshowLabel.setVisibility(View.VISIBLE);
				unshowLabel.setText(1 + "");
			}

		} else {
			unshowLabel.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 刷新未读消息数
	 */
	public void updateUnreadLabel() {
		int count = getUnreadMsgCountTotal();
		if (count > 0) {
			// if(count > 99){
			// unreadLabel.setText("99+");
			// }else{
			// unreadLabel.setText(String.valueOf(count));
			// }
			unreadLabel.setVisibility(View.VISIBLE);
		} else {
			unreadLabel.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 获取未读消息数
	 * 
	 * @return
	 */
	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		int chatroomUnreadMsgCount = 0;
		unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
		for (EMConversation conversation : EMChatManager.getInstance()
				.getAllConversations().values()) {
			if (conversation.getType() == EMConversationType.ChatRoom)
				chatroomUnreadMsgCount = chatroomUnreadMsgCount
						+ conversation.getUnreadMsgCount();
		}
		return unreadMsgCountTotal - chatroomUnreadMsgCount;
	}

	private void setCmdMessage(final String action, EMMessage msgContent) {
		if (action == null || TextUtils.isEmpty(action)) {
			return;
		}
		if (action.equals("circle_news")) {
			refreshUIWithCircles(true);
		}
	}

	public void refreshUIWithCircles(final boolean isShow) {
		runOnUiThread(new Runnable() {
			public void run() {
				if (isShow) {
				} else {
				}
			}
		});
	}

	@Override
	public void onAttachFragment(Fragment fragment) {
		super.onAttachFragment(fragment);
		if (home_pager == null && fragment instanceof TabHomeNew) {
			home_pager = (TabHomeNew) fragment;
		} else if (chat_pager == null && fragment instanceof TabChat) {
			chat_pager = (TabChat) fragment;
		} else if (mine_pager == null && fragment instanceof TabMine) {
			mine_pager = (TabMine) fragment;
		}else if(tabGrowTree==null && fragment instanceof TabGrowTree){
			tabGrowTree=(TabGrowTree) fragment;
		}/* else if (file_page == null && fragment instanceof TabFileTree) {
			file_page = (TabFileTree) fragment;
		}else if (live_pager == null && fragment instanceof TabGrow) {
			live_pager = (TabGrow) fragment;
		} */
	}

	@Override
	protected void onInit() {
		
		mBottomBg = (ImageView) findViewById(R.id.menu_bottom_bg);
		unreadLabel = (TextView) findViewById(R.id.chat_message_tips);
		unshowLabel = (TextView) findViewById(R.id.tree_message_tips);
		manager = getSupportFragmentManager();
		mBottomRdg = (RadioGroup) findViewById(R.id.bottom_tab_rdg);
		fragmentCheck(R.id.home_tab);
		rb_center = (RadioButton) findViewById(R.id.menu_tab);
		arcMenu = (ArcMenu) findViewById(R.id.arc_menu_button);
		initArcMenu(arcMenu, ITEM_DRAWABLES);
		main_root = (RelativeLayout) findViewById(R.id.main_root);

		dbHelper = new CupboardSQLiteOpenHelper(this);
		sqlDb = dbHelper.getWritableDatabase();
		menuWindow = new MenuWindow(this, this);

		imagePicker = ImagePicker.getInstance();
		imagePicker.setImageLoader(new GlideImageLoader());// 设置图片加载器
		imagePicker.setShowCamera(false); // 不显示拍照按钮
		imagePicker.setCrop(false); // 允许裁剪（单选才有效）
		imagePicker.setSaveRectangle(true); // 是否按矩形区域保存
		imagePicker.setSelectLimit(9); // 选中数量限制
		imagePicker.setMultiMode(true);

	}

	@Override
	protected void onData() {
		if (getIntent() != null) {
			isFileTree = getIntent().getBooleanExtra("isFree", false);
			if (isFileTree) {
				((RadioButton) mBottomRdg.getChildAt(1)).setChecked(true);
			}

		}
		userinfo = CustomerUtil.getUserInfo(this);
		mBottomRdg.setOnCheckedChangeListener(this);
		// unregister this event listener when this activity enters the
		// background
		EMHelper sdkHelper = EMHelper.getInstance();
		sdkHelper.pushActivity(this);
		// register the event listener when enter the foreground
		EMChatManager.getInstance().registerEventListener(
				this,
				new EMNotifierEvent.Event[] {
						EMNotifierEvent.Event.EventNewMessage,
						EMNotifierEvent.Event.EventOfflineMessage,
						EMNotifierEvent.Event.EventNewCMDMessage,
						EMNotifierEvent.Event.EventConversationListChanged });
		registerBroadcastReceiver();

		if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {
			loadingParentsChildren();
		} else {
			loadingChildClassInfos();
		}
		loadingGrowTreeDatas();

	}

	private void loadingGrowTreeDatas() {
		if (NetWorkUtils.isNetworkAvailable(mContext)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("class_manager_id", mSpUtil.getChildClassId());
			sendMap.put("grade_id", mSpUtil.getChildGradeId());
			sendMap.put("school_id", mSpUtil.getChildSchoolId());
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_GROW_TREE_DATAS, sendMap);
			MyAsyncHttp.get(mContext, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						TreeHomeBean getData = ResponseUtils.getTreeHomeDatas(
								mContext, result);
						if (getData != null) {
							oldTreeLeaf = Integer.parseInt(getData.peibancount);
						}
					}
				}
			});
		} else {
			ShowToast.showShort(mContext, R.string.net_break);// 提示无网络
		}
	}

	private void loadingParentsChildren() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_PARENTS_CHILDREN_API, sendMap);
			Log.e("===", requestUrl);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						List<ChildInfo> parentOwnStudent = ResponseUtils
								.getMyChildren(mContext, result);
						if (parentOwnStudent != null
								&& parentOwnStudent.size() > 0) {

							cupboard().withDatabase(sqlDb).delete(
									ChildBean.class, "_id < ?", "10000");// clear//
																			// old//
																			// datas

							for (ChildInfo child : parentOwnStudent) {
								ChildBean dbChild = new ChildBean();
								dbChild.parent_id = mSpUtil.getUserId();
								dbChild.child_id = child.studentInfo.id;
								dbChild.id_code = "";
								dbChild.im_user_id = child.studentInfo.im_user_id;
								dbChild.name = child.studentInfo.name;
								dbChild.nickname = child.studentInfo.nickname;
								dbChild.mobile = child.studentInfo.mobile;

								dbChild.class_id = child.classInfo.class_manager_id;
								dbChild.class_name = child.classInfo.name;

								dbChild.grade_id = child.classInfo.grade_id;
								dbChild.grade_name = child.classInfo.get_gradeInof.name;

								dbChild.school_id = child.classInfo.schoolInfo.id;
								dbChild.school_name = child.classInfo.schoolInfo.name;

								dbChild.avatar_00 = child.studentInfo.avatarInfo.fileurl_00;
								dbChild.avatar_01 = child.studentInfo.avatarInfo.fileurl_01;
								dbChild.avatar_02 = child.studentInfo.avatarInfo.fileurl_02;
								dbChild.avatar_03 = child.studentInfo.avatarInfo.fileurl_03;
								cupboard().withDatabase(sqlDb).put(dbChild);

								loadingClassMembers(
										child.classInfo.class_manager_id,
										child.classInfo.name);
							}
						}
					} else {
						ShowToast.showShort(mContext, result);
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void loadingChildClassInfos() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("student_id", mSpUtil.getCurrentChildId());
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_CHILD_CLASSINFO_API, sendMap);

			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						UClassInfo childclass = ResponseUtils
								.getMyChildClassInfo(mContext, result);

						if (childclass != null) {
							mSpUtil.setChildClassId(childclass.class_manager_id);
							mSpUtil.setChildGradeId(childclass.grade_id);
							mSpUtil.setChildSchoolId(childclass.schoolInfo.id);
							mSpUtil.setClassName(childclass.name);
							mSpUtil.setSchoolName(childclass.schoolInfo.name);
							cupboard().withDatabase(sqlDb).delete(
									ChildBean.class, "_id < ?", "10000");// clear//
																			// old//
																			// datas

							ChildBean dbChild = new ChildBean();
							dbChild.parent_id = mSpUtil.getUserId();
							dbChild.child_id = mSpUtil.getCurrentChildId();
							if (userinfo != null) {
								dbChild.id_code = userinfo.id_code;
								dbChild.im_user_id = userinfo.im_user_id;
								dbChild.name = userinfo.name;
								dbChild.nickname = userinfo.nickname;
								dbChild.mobile = userinfo.mobile;
								dbChild.avatar_00 = userinfo.avatarInfo.fileurl_00;
								dbChild.avatar_01 = userinfo.avatarInfo.fileurl_01;
								dbChild.avatar_02 = userinfo.avatarInfo.fileurl_02;
								dbChild.avatar_03 = userinfo.avatarInfo.fileurl_03;
							} else {
								dbChild.id_code = "";
								dbChild.im_user_id = "";
								dbChild.name = "";
								dbChild.nickname = "";
								dbChild.mobile = "";
								dbChild.avatar_00 = "";
								dbChild.avatar_01 = "";
								dbChild.avatar_02 = "";
								dbChild.avatar_03 = "";
							}

							dbChild.class_id = childclass.class_manager_id;
							dbChild.class_name = childclass.name;

							dbChild.grade_id = childclass.get_gradeInof.id;
							dbChild.grade_name = childclass.get_gradeInof.name;

							dbChild.school_id = childclass.schoolInfo.id;
							dbChild.school_name = childclass.schoolInfo.name;

							cupboard().withDatabase(sqlDb).put(dbChild);

							loadingClassMembers(childclass.class_manager_id,
									childclass.name);
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void loadingClassMembers(final String classId,
			final String className) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("token", mSpUtil.getToken());
			sendMap.put("class_id", classId);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.GET_CLASS_MEMBERS_API, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						List<MyClassStudent> studentLists = ResponseUtils
								.getClassMembers(mContext, result, classId,
										className);
						if (studentLists != null && studentLists.size() > 0) {
							cupboard().withDatabase(sqlDb).delete(
									MyClassStudent.class, "class_id = ?",
									classId);
							for (MyClassStudent student : studentLists) {
								cupboard().withDatabase(sqlDb).put(student);
							}
						}
					} else {
						ShowToast
								.showShort(mContext, NetWorkApi.REQUEST_FAILED);
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	private void initArcMenu(ArcMenu menu, int[] itemDrawables) {
		menu.setCenterImageId(R.drawable.menu_arc);
		final int itemCount = itemDrawables.length;
		for (int i = 0; i < itemCount; i++) {
			ImageView item = new ImageView(this); // 如果要区分三个按钮的点击事件，给其设置唯一的id即可
			item.setImageResource(itemDrawables[i]);
			menu.addItem(item, new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(WriteRecordActivity.class);
				}
			});
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		fragmentCheck(checkedId);
	}

	private void hideAll(FragmentTransaction transaction) {
		if (home_pager != null) {
			transaction.hide(home_pager);
		}
		
		if (chat_pager != null) {
			transaction.hide(chat_pager);
		}
		if (mine_pager != null) {
			transaction.hide(mine_pager);
		}
		if(tabGrowTree!=null){
			transaction.hide(tabGrowTree);
		}
	/*	if (file_page != null) {
			transaction.hide(file_page);
		}if (live_pager != null) {
			transaction.hide(live_pager);
		}*/
	}

	/*public void changeTreeFragment(boolean isFile) {
		LogUtil.e("changeFragment回调值为" + isFile);
		isFileTree = isFile;

		FragmentTransaction transaction = manager.beginTransaction();
		if (isFileTree) {
			hideAll(transaction);
			if (file_page == null) {
				file_page = new TabFileTree();
				transaction.add(R.id.content, file_page);
			}
			transaction.show(file_page);
			transaction.commit();
		} else {
			hideAll(transaction);
			if (live_pager == null) {
				live_pager = new TabGrow();
				Bundle bundle = new Bundle();
				bundle.putInt("oldTreeLeaf", oldTreeLeaf);
				live_pager.setArguments(bundle);
				transaction.add(R.id.content, live_pager);
			}
			transaction.show(live_pager);
			transaction.commit();
		}
	}*/

	private void fragmentCheck(int id) {
		FragmentTransaction transaction = manager.beginTransaction();
		mBottomBg.setVisibility(View.VISIBLE);

		switch (id) {
		case R.id.home_tab:
			position=0;
			
			break;
		case R.id.grow_tab:
			position=1;
			hideAll(transaction);
			if (tabGrowTree == null) {
				tabGrowTree = new TabGrowTree();
				transaction.add(R.id.content, tabGrowTree);
			}
			transaction.show(tabGrowTree);
			transaction.commit();
			//changeTreeFragment(isFileTree);
			break;
		case R.id.menu_tab:
			((RadioButton)mBottomRdg.getChildAt(this.position)).setChecked(true);
			
			if (menuWindow != null) {
				menuWindow.showPopupWindow(main_root);
			}
			break;
		case R.id.chat_tab:
			position=3;
			hideAll(transaction);
			if (chat_pager == null) {
				chat_pager = new TabChat();
				transaction.add(R.id.content, chat_pager);
			}
			transaction.show(chat_pager);
			transaction.commit();
			break;
		case R.id.mine_tab:
			position=4;
			hideAll(transaction);
			if (mine_pager == null) {
				mine_pager = new TabMine();
				transaction.add(R.id.content, mine_pager);
			}
			transaction.show(mine_pager);
			transaction.commit();
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!isConflict && !isCurrentAccountRemoved) {
			updateUnreadLabel();
		}
		updateTreeLabel();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	private void registerBroadcastReceiver() {
		broadcastManager = LocalBroadcastManager.getInstance(this);
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
		intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
		broadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				updateUnreadLabel();
			}
		};
		broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
		childReceiver = new ChildReceiver();
		IntentFilter filter = new IntentFilter("child");
		registerReceiver(childReceiver, filter);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putBoolean("isConflict", isConflict);
		outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		instance = null;
		if (conflictBuilder != null) {
			conflictBuilder.create().dismiss();
			conflictBuilder = null;
		}
		EMChatManager.getInstance().unregisterEventListener(this);
		EMHelper sdkHelper = EMHelper.getInstance();
		sdkHelper.popActivity(this);
		broadcastManager.unregisterReceiver(broadcastReceiver);
		unregisterReceiver(childReceiver);
	}

	private android.app.AlertDialog.Builder conflictBuilder;
	private android.app.AlertDialog.Builder accountRemovedBuilder;
	private boolean isConflictDialogShow;
	private boolean isAccountRemovedDialogShow;

	/**
	 * 显示帐号在别处登录dialog
	 */
	private void showConflictDialog() {
		isConflictDialogShow = true;
		EMHelper.getInstance().logout(false, null);
		String st = getResources().getString(R.string.Logoff_notification);
		if (!MenuActivity.this.isFinishing()) {
			// clear up global variables
			try {
				if (conflictBuilder == null)
					conflictBuilder = new android.app.AlertDialog.Builder(this);
				conflictBuilder.setTitle(st);
				conflictBuilder.setMessage(R.string.connect_conflict);
				conflictBuilder.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								conflictBuilder = null;
								finish();
								startActivity(LoginActivity.class);
							}
						});
				conflictBuilder.setCancelable(false);
				conflictBuilder.create().show();
				isConflict = true;
			} catch (Exception e) {

			}
		}
	}

	/**
	 * 帐号被移除的dialog
	 */
	private void showAccountRemovedDialog() {
		isAccountRemovedDialogShow = true;
		EMHelper.getInstance().logout(true, null);
		String st5 = getResources().getString(R.string.Remove_the_notification);
		if (!MenuActivity.this.isFinishing()) {
			// clear up global variables
			try {
				if (accountRemovedBuilder == null)
					accountRemovedBuilder = new android.app.AlertDialog.Builder(
							this);
				accountRemovedBuilder.setTitle(st5);
				accountRemovedBuilder.setMessage("您的账号被删除");
				accountRemovedBuilder.setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								accountRemovedBuilder = null;
								finish();
								startActivity(LoginActivity.class);
							}
						});
				accountRemovedBuilder.setCancelable(false);
				accountRemovedBuilder.create().show();
				isCurrentAccountRemoved = true;
			} catch (Exception e) {

			}
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)
				&& !isConflictDialogShow) {
			showConflictDialog();
		} else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false)
				&& !isAccountRemovedDialogShow) {
			showAccountRemovedDialog();
		}
		isFileTree = intent.getBooleanExtra("isFree", false);
		if (isFileTree) {
			((RadioButton) mBottomRdg.getChildAt(1)).setChecked(true);
			Log.e("===", true + "true");
		}
	}

	long backTime;

	@Override
	public void onBackPressed() {
		if(menuWindow.isShowing()){
			menuWindow.showAsDropDown(main_root);
		}else{
			if (System.currentTimeMillis() - backTime <= 1500) {
				ActivitiesStack.getInstance().popAll(true);
			} else {
				backTime = System.currentTimeMillis();
				showToast("再按一次退出应用");
			}
		}
		
	}

	public void dismissBackgroundImg() {
		mBottomBg.setVisibility(View.INVISIBLE);
	}

	@Override
	public void onClickClubWindowListener(int position) {
		switch (position) {
		case 0: // 中间的按钮
			if (menuWindow != null) {
				menuWindow.setOnDismissListener(null);
				menuWindow.showPopupWindow(main_root);
			}
			break;
		case 1: // 发记录
			menuWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					startActivity(WriteRecordActivity.class);
				}
			});

			break;
		case 2: // 拍照
			LogUtil.e("USER_PERMISSION:"
					+ ContextCompat.checkSelfPermission(this,
							"android.permission.CAMERA"));
			LogUtil.e("USER_GRANTED:" + PackageManager.PERMISSION_GRANTED);
			LogUtil.e("USER_DENIED:" + PackageManager.PERMISSION_DENIED);

			menuWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					if (ContextCompat.checkSelfPermission(mContext,
							"android.permission.CAMERA") == PackageManager.PERMISSION_DENIED) {
						MPermissions.requestPermissions(MenuActivity.this,
								EaseConstant.REQUECT_CODE_SDCARD,
								"android.permission.CAMERA");
					} else {
						imagePicker.takePicture(MenuActivity.this,
								GET_IMAGE_VIA_CAMERA);
					}
				}
			});

			break;
		case 3: // 选相册
			menuWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					imagePicker.setSelectLimit(9);
					Intent intent = new Intent(mContext,
							ImageGridActivity.class);
					startActivityForResult(intent,
							MContants.SELECT_WECHAT_DCIM_CODE);
				}
			});

			break;
		case 4: // 进入到填写身高和体重的界面
			menuWindow.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
				
					Intent intent = new Intent(mContext,
							BodyActivity.class);
					startActivity(intent);
				}
			});

			break;
		default:
			break;
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		postImages.clear();
		if (requestCode == GET_IMAGE_VIA_CAMERA && resultCode == RESULT_OK) {
			// 发送广播通知图片增加了
			ImagePicker.galleryAddPic(this, imagePicker.getTakeImageFile());
			ImageItem imageItem = new ImageItem();
			imageItem.path = imagePicker.getTakeImageFile().getAbsolutePath();
			imagePicker.clearSelectedImages();
			imagePicker.addSelectedImageItem(0, imageItem, true);
			postImages.add(imageItem);

		} else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
			if (data != null
					&& requestCode == MContants.SELECT_WECHAT_DCIM_CODE) {
				@SuppressWarnings("unchecked")
				ArrayList<ImageItem> images = (ArrayList<ImageItem>) data
						.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
				if (images != null && images.size() > 0) {
					postImages.clear(); // 清除以前选择的照片
					if (images.size() > 9) {
						postImages.addAll(images);
					} else {
						postImages.addAll(images);
					}
				}
			}
		}
		Intent intent = new Intent(MenuActivity.this, WriteRecordActivity.class);
		intent.putExtra("pics", (Serializable) postImages);
		startActivity(intent);
	}

	public class ChildReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			if (arg1.getAction().equals("child")) {
				if (mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)) {
					loadingParentsChildren();
				} else {
					loadingChildClassInfos();
				}
			} else if (arg1.getAction().equals(
					MyHomeWkDetailsActivity.HOMEWORK_CONFIRM_PARENT)) {
				  updateTreeLabel();
			}
		}

	}

	public void showTabHome(){
		FragmentTransaction transaction = manager.beginTransaction();
		hideAll(transaction);
		if (home_pager == null) {
			home_pager = new TabHomeNew();
			transaction.add(R.id.content, home_pager);
		}
		transaction.show(home_pager);
		transaction.commit();
	}
	public void onBack(View v){
		((RadioButton)mBottomRdg.getChildAt(0)).setChecked(true);
		showTabHome();
		
	}
}
